<template>
  <div class="finance-health-container">
    <!-- 顶部概览卡片 -->
    <el-row :gutter="20" class="overview-cards">
      <el-col :span="6" v-for="(card, index) in overviewCards" :key="index">
        <el-card shadow="hover" class="overview-card" :class="getHealthClass(card.score)">
          <div class="card-header">
            <el-icon class="card-icon"><component :is="card.icon" /></el-icon>
            <span class="card-title">{{ card.title }}</span>
          </div>
          <div class="card-content">
            <div class="score">{{ card.score }}</div>
            <div class="status">{{ getHealthStatus(card.score) }}</div>
            <div class="trend" :class="card.trend > 0 ? 'up' : 'down'">
              <el-icon><ArrowUp v-if="card.trend > 0" /><ArrowDown v-else /></el-icon>
              {{ Math.abs(card.trend) }}%
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 主要图表区域 -->
    <el-row :gutter="20" class="main-charts">
      <!-- 健康分变化曲线 -->
      <el-col :span="16">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>财务健康分变化趋势</span>
              <el-button-group>
                <el-button size="small" @click="switchDataSet(0)" :type="currentDataSet === 0 ? 'primary' : ''">用户A</el-button>
                <el-button size="small" @click="switchDataSet(1)" :type="currentDataSet === 1 ? 'primary' : ''">用户B</el-button>
              </el-button-group>
            </div>
          </template>
          <div ref="healthTrendChart" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 综合健康评分 -->
      <el-col :span="8">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <span>综合健康评分</span>
          </template>
          <div ref="healthScoreChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 五大维度分析 -->
    <el-row :gutter="20" class="dimension-charts">
      <!-- 负债承受力雷达图 -->
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <span>负债承受力雷达图</span>
          </template>
          <div ref="debtRadarChart" class="chart-container"></div>
        </el-card>
      </el-col>

      <!-- 资产流动性热力图 -->
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <span>资产流动性热力图</span>
          </template>
          <div ref="liquidityHeatmapChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 收入稳定性和消费分析 -->
    <el-row :gutter="20" class="analysis-charts">
      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <span>收入稳定性指数</span>
          </template>
          <div ref="incomeStabilityChart" class="chart-container"></div>
        </el-card>
      </el-col>

      <el-col :span="12">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <span>消费合理性分析</span>
          </template>
          <div ref="consumptionChart" class="chart-container"></div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 详细指标表格 -->
    <el-row :gutter="20" class="detail-section">
      <el-col :span="24">
        <el-card shadow="hover" class="chart-card">
          <template #header>
            <div class="card-header">
              <span>详细财务指标</span>
              <el-button type="primary" @click="generateReport" :loading="reportLoading">
                <el-icon><Download /></el-icon>
                生成报告
              </el-button>
            </div>
          </template>
          <el-table :data="detailMetrics" stripe>
            <el-table-column prop="category" label="维度" width="120" />
            <el-table-column prop="metric" label="指标" />
            <el-table-column prop="value" label="当前值" width="100" />
            <el-table-column prop="score" label="评分" width="80">
              <template #default="scope">
                <el-tag :type="getScoreTagType(scope.row.score)">{{ scope.row.score }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="scope">
                <el-tag :type="getHealthTagType(scope.row.score)">{{ getHealthStatus(scope.row.score) }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="suggestion" label="建议" />
          </el-table>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { ArrowUp, ArrowDown, Download, TrendCharts, Wallet, CreditCard, Money } from '@element-plus/icons-vue'
import * as echarts from 'echarts'

// 响应式数据
const currentDataSet = ref(0)
const reportLoading = ref(false)

// 图表实例
const healthTrendChart = ref(null)
const healthScoreChart = ref(null)
const debtRadarChart = ref(null)
const liquidityHeatmapChart = ref(null)
const incomeStabilityChart = ref(null)
const consumptionChart = ref(null)

let healthTrendChartInstance = null
let healthScoreChartInstance = null
let debtRadarChartInstance = null
let liquidityHeatmapChartInstance = null
let incomeStabilityChartInstance = null
let consumptionChartInstance = null

// 模拟数据 - 两组用户数据
const mockData = [
  {
    // 用户A数据
    overallScore: 75,
    trend: 5.2,
    monthlyScores: [68, 70, 72, 69, 71, 73, 75, 77, 74, 76, 78, 75],
    events: [
      { month: 3, event: '大额投资', type: 'investment' },
      { month: 7, event: '收入增长', type: 'income' },
      { month: 10, event: '房贷支出', type: 'expense' }
    ],
    dimensions: {
      income: 78,
      debt: 72,
      liquidity: 80,
      consumption: 71,
      credit: 85
    }
  },
  {
    // 用户B数据
    overallScore: 62,
    trend: -2.8,
    monthlyScores: [70, 68, 65, 63, 61, 59, 62, 64, 63, 61, 60, 62],
    events: [
      { month: 2, event: '收入骤降', type: 'income_drop' },
      { month: 5, event: '大额支出', type: 'expense' },
      { month: 9, event: '债务重组', type: 'debt' }
    ],
    dimensions: {
      income: 58,
      debt: 65,
      liquidity: 70,
      consumption: 55,
      credit: 62
    }
  }
]

// 概览卡片数据
const overviewCards = ref([
  {
    title: '综合健康分',
    score: 75,
    trend: 5.2,
    icon: 'TrendCharts'
  },
  {
    title: '收入稳定性',
    score: 78,
    trend: 3.1,
    icon: 'Money'
  },
  {
    title: '负债承受力',
    score: 72,
    trend: -1.5,
    icon: 'CreditCard'
  },
  {
    title: '资产流动性',
    score: 80,
    trend: 2.8,
    icon: 'Wallet'
  }
])

// 详细指标数据
const detailMetrics = ref([
  { category: '收入稳定性', metric: '月收入变异系数', value: '0.15', score: 78, suggestion: '收入相对稳定，建议增加被动收入来源' },
  { category: '收入稳定性', metric: '收入增长率', value: '8.5%', score: 82, suggestion: '收入增长良好' },
  { category: '收入稳定性', metric: '收入来源多样性', value: '3个', score: 75, suggestion: '可考虑增加收入来源' },
  { category: '负债承受力', metric: '负债收入比', value: '35%', score: 72, suggestion: '负债比例适中，注意控制' },
  { category: '负债承受力', metric: '月供收入比', value: '28%', score: 75, suggestion: '月供压力可控' },
  { category: '负债承受力', metric: '信贷利用率', value: '45%', score: 68, suggestion: '建议降低信贷利用率' },
  { category: '资产流动性', metric: '流动资产比例', value: '65%', score: 80, suggestion: '流动性充足' },
  { category: '资产流动性', metric: '应急资金覆盖月数', value: '6个月', score: 85, suggestion: '应急资金充足' },
  { category: '消费合理性', metric: '消费支出比', value: '70%', score: 71, suggestion: '消费比例合理，可适当增加储蓄' },
  { category: '消费合理性', metric: '必需品支出比', value: '45%', score: 78, suggestion: '必需品支出控制良好' },
  { category: '信用健康度', metric: '信用评分', value: '750', score: 85, suggestion: '信用状况优秀' },
  { category: '信用健康度', metric: '逾期记录', value: '0次', score: 100, suggestion: '保持良好还款记录' }
])

// 健康状态判断
const getHealthStatus = (score) => {
  if (score > 80) return '健康'
  if (score > 60) return '亚健康'
  if (score > 40) return '风险'
  return '高危'
}

const getHealthClass = (score) => {
  if (score > 80) return 'health-good'
  if (score > 60) return 'health-fair'
  if (score > 40) return 'health-risk'
  return 'health-danger'
}

const getHealthTagType = (score) => {
  if (score > 80) return 'success'
  if (score > 60) return 'warning'
  if (score > 40) return 'danger'
  return 'danger'
}

const getScoreTagType = (score) => {
  if (score > 80) return 'success'
  if (score > 60) return ''
  if (score > 40) return 'warning'
  return 'danger'
}

// 切换数据集
const switchDataSet = (index) => {
  currentDataSet.value = index
  updateChartsData()
  updateOverviewCards()
}

// 更新概览卡片
const updateOverviewCards = () => {
  const data = mockData[currentDataSet.value]
  overviewCards.value[0].score = data.overallScore
  overviewCards.value[0].trend = data.trend
  overviewCards.value[1].score = data.dimensions.income
  overviewCards.value[2].score = data.dimensions.debt
  overviewCards.value[3].score = data.dimensions.liquidity
}

// 初始化健康趋势图表
const initHealthTrendChart = () => {
  healthTrendChartInstance = echarts.init(healthTrendChart.value)
  updateHealthTrendChart()
}

const updateHealthTrendChart = () => {
  const data = mockData[currentDataSet.value]
  const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'cross' }
    },
    legend: {
      data: ['健康分', '事件标注']
    },
    xAxis: {
      type: 'category',
      data: months,
      axisLine: { lineStyle: { color: '#ddd' } }
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 100,
      axisLine: { lineStyle: { color: '#ddd' } }
    },
    series: [
      {
        name: '健康分',
        type: 'line',
        data: data.monthlyScores,
        smooth: true,
        lineStyle: { width: 3, color: '#409EFF' },
        areaStyle: {
          color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
            { offset: 0, color: 'rgba(64, 158, 255, 0.3)' },
            { offset: 1, color: 'rgba(64, 158, 255, 0.1)' }
          ])
        },
        markPoint: {
          data: data.events.map(event => ({
            coord: [event.month - 1, data.monthlyScores[event.month - 1]],
            name: event.event,
            itemStyle: {
              color: event.type === 'income' ? '#67C23A' : 
                     event.type === 'expense' ? '#F56C6C' : '#E6A23C'
            }
          }))
        }
      }
    ]
  }
  
  healthTrendChartInstance.setOption(option)
}

// 初始化综合评分图表
const initHealthScoreChart = () => {
  healthScoreChartInstance = echarts.init(healthScoreChart.value)
  updateHealthScoreChart()
}

const updateHealthScoreChart = () => {
  const data = mockData[currentDataSet.value]
  const score = data.overallScore
  
  const option = {
    series: [
      {
        type: 'gauge',
        startAngle: 180,
        endAngle: 0,
        center: ['50%', '75%'],
        radius: '90%',
        min: 0,
        max: 100,
        splitNumber: 4,
        axisLine: {
          lineStyle: {
            width: 6,
            color: [
              [0.4, '#F56C6C'],
              [0.6, '#E6A23C'],
              [0.8, '#F7BA2A'],
              [1, '#67C23A']
            ]
          }
        },
        pointer: {
          icon: 'path://M12.8,0.7l12,40.1H0.7L12.8,0.7z',
          length: '12%',
          width: 20,
          offsetCenter: [0, '-60%'],
          itemStyle: { color: 'auto' }
        },
        axisTick: { length: 12, lineStyle: { color: 'auto', width: 2 } },
        splitLine: { length: 20, lineStyle: { color: 'auto', width: 5 } },
        axisLabel: {
          color: '#464646',
          fontSize: 20,
          distance: -60,
          formatter: function (value) {
            if (value === 100) return '健康'
            if (value === 80) return '亚健康'
            if (value === 60) return '风险'
            if (value === 40) return '高危'
            return ''
          }
        },
        title: {
          offsetCenter: [0, '-20%'],
          fontSize: 20
        },
        detail: {
          fontSize: 30,
          offsetCenter: [0, '-35%'],
          valueAnimation: true,
          formatter: function (value) {
            return Math.round(value) + '分'
          },
          color: 'auto'
        },
        data: [{ value: score, name: '综合评分' }]
      }
    ]
  }
  
  healthScoreChartInstance.setOption(option)
}

// 初始化负债雷达图
const initDebtRadarChart = () => {
  debtRadarChartInstance = echarts.init(debtRadarChart.value)
  updateDebtRadarChart()
}

const updateDebtRadarChart = () => {
  const data = mockData[currentDataSet.value]
  
  const option = {
    tooltip: {},
    legend: {
      data: ['当前状态', '理想状态']
    },
    radar: {
      indicator: [
        { name: '负债收入比', max: 100 },
        { name: '月供压力', max: 100 },
        { name: '信贷利用率', max: 100 },
        { name: '还款能力', max: 100 },
        { name: '债务结构', max: 100 },
        { name: '担保风险', max: 100 }
      ]
    },
    series: [
      {
        name: '负债承受力',
        type: 'radar',
        data: [
          {
            value: [72, 75, 68, 80, 70, 85],
            name: '当前状态',
            areaStyle: { color: 'rgba(64, 158, 255, 0.3)' }
          },
          {
            value: [85, 85, 85, 85, 85, 85],
            name: '理想状态',
            areaStyle: { color: 'rgba(103, 194, 58, 0.2)' }
          }
        ]
      }
    ]
  }
  
  debtRadarChartInstance.setOption(option)
}

// 初始化流动性热力图
const initLiquidityHeatmapChart = () => {
  liquidityHeatmapChartInstance = echarts.init(liquidityHeatmapChart.value)
  updateLiquidityHeatmapChart()
}

const updateLiquidityHeatmapChart = () => {
  const assets = ['现金', '活期存款', '定期存款', '货币基金', '股票', '债券', '房产', '其他']
  const timeframes = ['即时', '1天', '1周', '1月', '3月', '6月', '1年', '1年+']
  
  const data = []
  for (let i = 0; i < assets.length; i++) {
    for (let j = 0; j < timeframes.length; j++) {
      const value = Math.random() * 100
      data.push([j, i, Math.round(value)])
    }
  }
  
  const option = {
    tooltip: {
      position: 'top',
      formatter: function (params) {
        return `${assets[params.data[1]]}<br/>${timeframes[params.data[0]]}: ${params.data[2]}%`
      }
    },
    grid: {
      height: '50%',
      top: '10%'
    },
    xAxis: {
      type: 'category',
      data: timeframes,
      splitArea: { show: true }
    },
    yAxis: {
      type: 'category',
      data: assets,
      splitArea: { show: true }
    },
    visualMap: {
      min: 0,
      max: 100,
      calculable: true,
      orient: 'horizontal',
      left: 'center',
      bottom: '15%',
      inRange: {
        color: ['#313695', '#4575b4', '#74add1', '#abd9e9', '#e0f3f8', '#ffffcc', '#fee090', '#fdae61', '#f46d43', '#d73027', '#a50026']
      }
    },
    series: [
      {
        name: '流动性',
        type: 'heatmap',
        data: data,
        label: {
          show: true
        },
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }
    ]
  }
  
  liquidityHeatmapChartInstance.setOption(option)
}

// 初始化收入稳定性图表
const initIncomeStabilityChart = () => {
  incomeStabilityChartInstance = echarts.init(incomeStabilityChart.value)
  updateIncomeStabilityChart()
}

const updateIncomeStabilityChart = () => {
  const months = ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
  const incomeData = [8500, 8200, 8800, 8600, 8900, 9200, 9500, 9300, 9100, 9400, 9600, 9200]
  const stabilityIndex = [75, 72, 78, 76, 80, 82, 85, 83, 81, 84, 86, 82]
  
  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: { type: 'cross' }
    },
    legend: {
      data: ['月收入', '稳定性指数']
    },
    xAxis: {
      type: 'category',
      data: months
    },
    yAxis: [
      {
        type: 'value',
        name: '收入(元)',
        position: 'left'
      },
      {
        type: 'value',
        name: '稳定性指数',
        position: 'right',
        max: 100
      }
    ],
    series: [
      {
        name: '月收入',
        type: 'bar',
        data: incomeData,
        itemStyle: { color: '#409EFF' }
      },
      {
        name: '稳定性指数',
        type: 'line',
        yAxisIndex: 1,
        data: stabilityIndex,
        lineStyle: { color: '#67C23A', width: 3 },
        smooth: true
      }
    ]
  }
  
  incomeStabilityChartInstance.setOption(option)
}

// 初始化消费分析图表
const initConsumptionChart = () => {
  consumptionChartInstance = echarts.init(consumptionChart.value)
  updateConsumptionChart()
}

const updateConsumptionChart = () => {
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      data: ['住房', '食品', '交通', '娱乐', '医疗', '教育', '其他']
    },
    series: [
      {
        name: '消费结构',
        type: 'pie',
        radius: ['40%', '70%'],
        avoidLabelOverlap: false,
        label: {
          show: false,
          position: 'center'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: '18',
            fontWeight: 'bold'
          }
        },
        labelLine: {
          show: false
        },
        data: [
          { value: 3500, name: '住房', itemStyle: { color: '#409EFF' } },
          { value: 1200, name: '食品', itemStyle: { color: '#67C23A' } },
          { value: 800, name: '交通', itemStyle: { color: '#E6A23C' } },
          { value: 600, name: '娱乐', itemStyle: { color: '#F56C6C' } },
          { value: 400, name: '医疗', itemStyle: { color: '#909399' } },
          { value: 500, name: '教育', itemStyle: { color: '#9C27B0' } },
          { value: 300, name: '其他', itemStyle: { color: '#FF9800' } }
        ]
      }
    ]
  }
  
  consumptionChartInstance.setOption(option)
}

// 更新所有图表数据
const updateChartsData = () => {
  updateHealthTrendChart()
  updateHealthScoreChart()
  updateDebtRadarChart()
}

// 生成报告
const generateReport = async () => {
  reportLoading.value = true
  try {
    // 这里应该调用后端API生成报告
    // const response = await generateFinanceHealthReport(currentDataSet.value)
    
    // 模拟API调用
    await new Promise(resolve => setTimeout(resolve, 2000))
    
    ElMessage.success('财务健康报告生成成功！')
  } catch (error) {
    ElMessage.error('报告生成失败，请重试')
  } finally {
    reportLoading.value = false
  }
}

// 窗口大小变化处理
const handleResize = () => {
  healthTrendChartInstance?.resize()
  healthScoreChartInstance?.resize()
  debtRadarChartInstance?.resize()
  liquidityHeatmapChartInstance?.resize()
  incomeStabilityChartInstance?.resize()
  consumptionChartInstance?.resize()
}

// 组件挂载
onMounted(async () => {
  await nextTick()
  
  // 初始化所有图表
  initHealthTrendChart()
  initHealthScoreChart()
  initDebtRadarChart()
  initLiquidityHeatmapChart()
  initIncomeStabilityChart()
  initConsumptionChart()
  
  // 监听窗口大小变化
  window.addEventListener('resize', handleResize)
})

// 组件卸载
onUnmounted(() => {
  window.removeEventListener('resize', handleResize)
  
  // 销毁图表实例
  healthTrendChartInstance?.dispose()
  healthScoreChartInstance?.dispose()
  debtRadarChartInstance?.dispose()
  liquidityHeatmapChartInstance?.dispose()
  incomeStabilityChartInstance?.dispose()
  consumptionChartInstance?.dispose()
})
</script>

<style scoped>
.finance-health-container {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

.overview-cards {
  margin-bottom: 20px;
}

.overview-card {
  height: 120px;
  border-radius: 8px;
  transition: all 0.3s ease;
}

.overview-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.overview-card.health-good {
  border-left: 4px solid #67C23A;
}

.overview-card.health-fair {
  border-left: 4px solid #E6A23C;
}

.overview-card.health-risk {
  border-left: 4px solid #F7BA2A;
}

.overview-card.health-danger {
  border-left: 4px solid #F56C6C;
}

.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 10px;
}

.card-icon {
  font-size: 24px;
  color: #409EFF;
  margin-right: 8px;
}

.card-title {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

.card-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.score {
  font-size: 32px;
  font-weight: bold;
  color: #303133;
}

.status {
  font-size: 12px;
  color: #909399;
}

.trend {
  display: flex;
  align-items: center;
  font-size: 12px;
  font-weight: 500;
}

.trend.up {
  color: #67C23A;
}

.trend.down {
  color: #F56C6C;
}

.main-charts,
.dimension-charts,
.analysis-charts,
.detail-section {
  margin-bottom: 20px;
}

.chart-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.chart-container {
  height: 300px;
  width: 100%;
}

.detail-section .chart-container {
  height: auto;
}

:deep(.el-card__header) {
  background-color: #fafafa;
  border-bottom: 1px solid #ebeef5;
  padding: 15px 20px;
  font-weight: 600;
  color: #303133;
}

:deep(.el-table) {
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  color: #606266;
  font-weight: 600;
}

:deep(.el-button-group .el-button) {
  padding: 5px 15px;
  font-size: 12px;
}

@media (max-width: 768px) {
  .finance-health-container {
    padding: 10px;
  }
  
  .overview-cards .el-col {
    margin-bottom: 10px;
  }
  
  .chart-container {
    height: 250px;
  }
}
</style>